import pymysql
import hashlib
from django.http import HttpResponse


db = pymysql.connect(host="localhost", user="devil",
                     password="123456", database="dict",
                     charset="utf8")
cur = db.cursor()


def search(request):
    return HttpResponse("This is the first")


def search2(request):
    return HttpResponse("This is the third")


def page_view(request, page):
    return HttpResponse(f"This is {page}")


def cal_view(request, num1, op, num2):
    if op == "add":
        result = num1 + num2
    elif op == "sub":
        result = num1 - num2
    elif op == "mul":
        result = num1 * num2
    elif op == "div":
        result = num1 / num2
    else:
        result = HttpResponse("ill")

    return HttpResponse(f"result:{result}")


def encryption(password):
    m = hashlib.md5()
    m.update(password.encode(encoding='utf-8'))
    encryption_md5 = m.hexdigest()
    return encryption_md5


def addr_view(request):
    print("method----->", request.method)
    print("GET----->", request.GET)
    #  < QueryDict: {'user': ['admin'], 'pwd': ['123456']} >
    return HttpResponse("result")


def log_in(request):
    if request.method == "GET":
        username = request.GET.get("username")
        password = request.GET.get("password")
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
    else:
        return HttpResponse("Error")
    sel = "select passwor from user_profile where username=%s"
    cur.execute(sel, [username])
    result = cur.fetchall()
    print("-------------------", result)
    if not result:
        return HttpResponse("Error")
    pwd_db = result[0][0]
    if pwd_db != password:
        return HttpResponse("Account Error")
    return HttpResponse(f"Congratulation:{username}")


def register(request):
    if request.method == "GET":
        data = request.GET
        username = data.get("username")
        password = data.get("password")
        password_again = data.get("password")
        email = data.get("email")
        phone = data.get("phone")
    elif request.method == "POST":
        data = request.POST
        username = data.get("username")
        password = data.get("password")
        password_again = data.get("password2")
        email = data.get("email")
        phone = data.get("phone")
    else:
        return HttpResponse("ill")

    if password != password_again:
        return HttpResponse("error")
    sel = "select username from user_profile where username=%s"
    result = cur.execute(sel, [username])
    if result:
        return HttpResponse("error")

    ins = "insert into user_profile(username, passwor, email, phone) values (%s, %s, %s, %s)"
    cur.execute(ins, [username, encryption(password), email, phone])
    db.commit()
    return HttpResponse("Congratulation")
